package cloud.example.eureka_client.service;

import cloud.example.eureka_client.mapper.CountMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author zjm
 * @date 2018/12/22.
 */
@Service
@Slf4j
public class CountService {
  private final static String CLIENT_ID = "client2";
  private RedisLockService redisLockService;
  private CountMapper countMapper;

  public CountService(RedisLockService redisLockService, CountMapper countMapper) {
    this.redisLockService = redisLockService;
    this.countMapper = countMapper;
  }

  public Integer count(Integer id) {
    try {
      if (redisLockService.lock(String.valueOf(id), CLIENT_ID)) {
        Integer currentCount = countMapper.getCount(id);
        currentCount++;
        countMapper.updateCount(id, currentCount);
        return currentCount;
      }
    } catch (Exception e) {
      log.error("exception occur when counting:", e);
    } finally {
      redisLockService.unLock(String.valueOf(id));
    }
    return null;
  }
}
